#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/9/22 0022 21:05
# @Author  : GXl
# @File    : views.py
# @Software: win10 Tensorflow1.13.1 python3.7
from config import Config
from flask import request,make_response
from . import api
import requests
from utils import logutils
from app import auth
from utils.apiutils import jsonData
import  time

"""
采用正则表达式，匹配所有的url，然后导向后端服务，后端服务返回后，接口返回数据。
本服务就是为了避免跨域请求
"""
logger = logutils.getlogger(__file__)
config=Config()


"""
测试相关
"""
@api.route("/test", methods=['GET', 'POST','DELETE','PUT'])
def test():
    return jsonData("test ok")

#专门匹配test结尾的测试url
@api.route("/<re(r'[a-zA-Z0-9/]+test$'):suburl>", methods=['GET', 'POST','DELETE','PUT'])
def maptest(suburl):
    logger.info('suburl={} method={} data={}'.format(suburl,request.method,str(request.data,'utf-8')))
    res=None
    baseurl=''
    for key,val in config.MICROSERVICES.items():
        urls=val['urls'].split(',')
        for item in urls:
            if request.path.startswith('/api/'+item):
                baseurl='http://{host}:{port}'.format_map(val)
                logger.info('匹配到url：{}'.format(baseurl))
                break
        if baseurl:
            break
    if not baseurl:
        logger.error('未匹配到任何url request.path='.format(request.path))
        raise Exception('未匹配到任何url request.path='.format(request.path))

    if request.method=='GET':
        res = requests.get(baseurl + request.path, headers=request.headers)
    if request.method == 'POST':
        res = requests.post(baseurl + request.path,data=request.data,headers=request.headers)
    if request.method == 'DELETE':
        res = requests.delete(baseurl + request.path,data=request.data, headers=request.headers)
    if request.method == 'PUT':
        res = requests.put(baseurl + request.path,data=request.data, headers=request.headers)
    if res==None:
        logger.error('请求suburl:{}无返回'.format(suburl))
        raise Exception('请求suburl:{}无返回'.format(suburl))

    response = make_response((res.content,res.status_code,{'Content-Type': res.headers['Content-Type']}))
    return response
"""
这里采用requirements
"""
@api.route("/<re(r'[a-zA-Z0-9/]+'):suburl>", methods=['GET', 'POST','DELETE','PUT'])
@auth.login_required
def main(suburl):
    logger.info('suburl={} method={} uuid={} data={}'.format(suburl,request.method,request.headers['uuid'],str(request.data,'utf-8')))
    res=None
    baseurl=''
    for key,val in config.MICROSERVICES.items():
        urls=val['urls'].split(',')
        for item in urls:
            if request.path.startswith('/api/'+item):
                baseurl='http://{host}:{port}'.format_map(val)
                logger.info('匹配到url：{}'.format(baseurl))
                break
        if baseurl:
            break
    if not baseurl:
        logger.error('未匹配到任何url request.path='.format(request.path))
        raise Exception('未匹配到任何url request.path='.format(request.path))

    starttime=time.time()
    if request.method=='GET':
        res = requests.get(baseurl + request.path, headers=request.headers,timeout=10)
    if request.method == 'POST':
        res = requests.post(baseurl + request.path,data=request.data,headers=request.headers,timeout=10)
    if request.method == 'DELETE':
        res = requests.delete(baseurl + request.path,data=request.data, headers=request.headers,timeout=10)
    if request.method == 'PUT':
        res = requests.put(baseurl + request.path,data=request.data, headers=request.headers,timeout=10)
    logger.info("status_code={} uuid={} spenttime={} text={}".format(res.status_code,request.headers['uuid'],time.time()-starttime,res.text))
    if str(res.status_code)!='200':
        logger.info("status_code非200，status_code为{},返回内容为：{}".format(res.status_code,res.text))

    response = make_response((res.content,res.status_code,{'Content-Type': res.headers['Content-Type']}))
    return response
